# coding=utf-8
import tornado.web

import WrapCursor
from CommonLib import *
from database.models.Controller import Controller
from database.models.ControllerPoint import ControllerPoint
from database.models.DatabaseCommon import *


class DelDeviceHandler(tornado.web.RequestHandler):
    __metaclass__ = ABCMeta

    def post(self):
        r = WrapCursor.WrapCursor()
        try:
            ojson = json.loads(self.request.body)
            idd = ojson['id']
            r = WrapCursor.WrapCursor()
            j = json.loads(self.request.body)
            ojson = j
            CheckJsonKeys(ojson)
            CheckAuth(ojson)
        except:
            self.write(r.Error('request data error'))
            return
        if idd is "*":
            self.write(r.Error('you are attach the server'))
            return

        session = Session()
        ctlp = session.query(ControllerPoint).filter_by(ControllerID=idd).all()
        for i in ctlp:
            session.delete(i)
        ctl = session.query(Controller).filter_by(id=idd).all()
        for i in ctl:
            session.delete(i)
        session.commit()
        self.write(r.Ok('success'))
